<template>
  <el-dialog
    title="导入数据预览确认"
    v-model="dialogVisible"
    width="80vw"
    @close="close"
  >
    <div style="width: 100%">
      <el-table
        :data="importTableList"
        border
        style="width: 100%"
        class="previewTable"
        table-layout="auto"
      >
        <!-- <el-table-column prop="deptName" label="归属部门名称">
          <template #default="scope">
            <p
              :class="{
                red: isRed(scope.row.deptName),
              }"
            >
              {{ scope.row.deptName.value }}
            </p>
            <p v-show="isRed(scope.row.deptName)" class="errMsg">
              {{ scope.row.deptName?.errMsg }}
            </p>
          </template>
        </el-table-column> -->
        <el-table-column prop="userName" label="用户名">
          <template #default="scope">
            <!-- <el-input type="text" v-model="scope.row.userName" /> -->
            <p
              :class="{
                red: isRed(scope.row.userName),
              }"
            >
              {{ scope.row.userName.value }}
            </p>
            <p v-show="isRed(scope.row.userName)" class="errMsg">
              {{ scope.row.userName.errMsg }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="nickName" label="姓名">
          <template #default="scope">
            <!-- <el-input type="text" v-model="scope.row.nickName" /> -->
            <p
              :class="{
                red: isRed(scope.row.nickName),
              }"
            >
              {{ scope.row.nickName.value }}
            </p>
            <p v-show="isRed(scope.row.nickName)" class="errMsg">
              {{ scope.row.nickName.errMsg }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
          <template #default="scope">
            <!-- <el-input type="text" v-model="scope.row.email" /> -->
            <p
              :class="{
                red: isRed(scope.row.email),
              }"
            >
              {{ scope.row.email.value }}
            </p>
            <p v-show="isRed(scope.row.email)" class="errMsg">
              {{ scope.row.email.errMsg }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="phonenumber" label="电话">
          <template #default="scope">
            <!-- <el-input type="text" v-model="scope.row.phonenumber" /> -->
            <p
              :class="{
                red: isRed(scope.row.phonenumber),
              }"
            >
              {{ scope.row.phonenumber.value }}
            </p>
            <p v-show="isRed(scope.row.phonenumber)" class="errMsg">
              {{ scope.row.phonenumber.errMsg }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="用户性别">
          <template #default="scope">
            <!-- <el-select v-model="scope.row.sex" placeholder="请选择" disabled>
                  <el-option label="男" value="0" />
                  <el-option label="女" value="1" />
                </el-select> -->
            <p v-if="scope.row.sex.value === '0'">男</p>
            <p v-else-if="scope.row.sex.value === '1'">女</p>
            <p v-else-if="scope.row.sex.value === '2'">未知</p>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <el-button @click="onImport(false)">取消</el-button>
      <el-button type="primary" @click="onImport(true)" :disabled="hasError"
        >确认导入</el-button
      >
    </template>
  </el-dialog>
</template>
<script setup>
import { validateObject, isRed } from "@/utils/validate";
import { importData } from "@/api/account";
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Array,
  },
});
const emit = defineEmits(["close"]);
const dialogVisible = computed({
  get() {
    return props.visible;
  },
  set(val) {
    emit("close", val);
  },
});
const close = () => {
  dialogVisible.value = false;
};
// 校验规则定义
const validationRules = {
  userName: (value) => {
    const errors = [];
    // if (!/^[A-Za-z0-9&]+$/.test(value)) errors.push('只能包含字母、数字和&符号');
    if (!value || value == null || value == undefined || value == "undefined")
      errors.push("用户名不能为空");
    return errors.length ? errors : null;
  },
  nickName: (value) => {
    const errors = [];
    // if (typeof value !== 'string') errors.push('必须是字符串');
    if (value.length > 20) errors.push("昵称不能超过20个字符");
    return errors.length ? errors : null;
  },
  email: (value) => {
    const errors = [];
    if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value))
      errors.push("无效的邮箱格式");
    return errors.length ? errors : null;
  },
  phonenumber: (value) => {
    const errors = [];
    if (!value || value == null || value == undefined || value == "undefined")
      errors.push("联系方式不能为空");
    if (!/^(1[3-9]\d{9})|(0\d{2,4}([- ]?)\d{7,8})$/.test(value))
      errors.push("联系方式格式不正确");
    return errors.length ? errors : null;
  },
};
const importTableList = ref([]);
const onImport = (bool) => {
  if (bool) {
    console.log("onImport", importTableList.value);
    const data = importTableList.value.map((item) => {
      return Object.keys(item).reduce((acc, key) => {
        if (key !== "message") {
          // 排除message字段
          acc[key] = item[key].value;
        }
        return acc;
      }, {});
    });

    // return;
    // const data = new FormData();
    // data.append("file", fileData.value);
    // data.append("updateSupport", true);
    const mapArr = [
      { str: "部门", key: "deptName" },
      { str: "用户", key: "userName" },
      { str: "昵称", key: "nickName" },
      { str: "手机", key: "phonenumber" },
      { str: "邮箱", key: "email" },
      { str: "性别", key: "sex" },
    ];
    importData({ sysUserImportVoList: data, updateSupport: false })
      .then((res) => {
        console.log(res, "resresres");
        if (res.code == 200) {
          // ElMessage.success("导入成功");
          // ElMessageBox.confirm(`${res.msg}`, "导入结果", {
          //   dangerouslyUseHTMLString: true,
          //   confirmButtonText: "确认",
          //   cancelButtonText: "关闭",
          //   showConfirmButton: false,
          //   type: "warning",
          // })
          //   .then(() => { })
          //   .catch(() => {
          //     importVisible.value = false;
          //     getUserLists(pageSize.value, currentPage.value);
          //   });
        }
      })
      .catch((res) => {
        // ElMessage.error(res.msg);
        console.log("导入失败vnoi", res);
        const result = res.data.map((item) => {
          // item是一条用户数据对象
          let err = "";
          const msg = item.message;
          if (msg) {
            mapArr.forEach((i) => {
              if (msg.includes(i.str)) {
                err = i.key;
              }
            });
          }
          const validRes = validateObject(item, validationRules);
          return Object.keys(item).reduce((acc, key) => {
            acc[key] = {
              value: item[key],
              noValidated: validRes[key] ? true : false,
              noPass: err == key ? true : false,
              // noPass: false,
              // errMsg: item.message || validRes[key],
              errMsg:
                err == key
                  ? item.message
                  : validRes[key]
                  ? validRes[key].join("，")
                  : "",
            };
            return acc;
          }, {});
        });
        console.log(result);
        importTableList.value = result;
      });
  } else {
    // importVisible.value = false;
    dialogVisible.value = false;
  }
};
const hasError = ref(false)
onMounted(() => {
  importTableList.value = props.data;
});
</script>
<style lang="scss" scoped>
.red {
  // color: red;
  color: #fc9d9d;
}
.errMsg {
  position: absolute;
  width: 93%;
  bottom: 0;
  font-size: 10px;
  line-height: 10px;
  // color: #fab6b6;
  color: rgb(250, 48, 48);
  text-align: center;
}
.previewTable {
  td {
    height: 60px;
  }
}
</style>
